import logging

from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect, redirect_to

from datetime import datetime

from google.appengine.ext import db
from monkeytest.model import TestRun, TestSuite, TestCase, TestCaseResult

from monkeytest.lib.base import BaseController, render

log = logging.getLogger(__name__)

class TestrunController(BaseController):
    def new(self):
        c.all_testsuites = TestSuite.select_list()
        return render("testrun/new.html")
    
    def create(self):
        if TestRun.gql("WHERE name = :1", request.params['name']).count() > 0:
            h.flash("Name exists")
            redirect_to("new_testrun")
            
        def make_key(key):
            return db.Key(key)
        testrun = TestRun()
        testrun.name = request.params['name']
        testrun.duedate = datetime.strptime(request.params['duedate'], "%d/%m/%Y").date()
        testrun.testsuites = map(make_key, request.params.getall("testsuites"))
        testrun.platforms = request.params['platforms'].split(',')

        testrun_key = db.put(testrun)
        for testsuite in testrun.testsuites:
            testcases = TestCase.gql("WHERE testsuite = :1", testsuite)
            for testcase in testcases:
                for platform in testrun.platforms:
                    result = TestCaseResult()
                    result.testrun = testrun_key
                    
                    result.testsuite = testsuite
                    
                    result.testcase = testcase.key()
                    result.summary = testcase.summary
                    result.instruction = testcase.instruction
                    result.expected_result = testcase.expected_result
                    
                    result.platform = platform
                    result.close = False
                    db.put(result)
        redirect_to("runtest", name=testrun.name)
        
    def show(self, name):
        testruns = TestRun.all()
        testruns.filter("name =", name)
            
        for testrun in testruns: 
            cases = TestCaseResult.all()
            cases.filter("testrun =", testrun.key())
            if request.params.has_key("result") and len(request.params["result"]) > 1:
                cases.filter("closed =", True)
                if request.params["result"] == "success":
                    cases.filter("success =", True)
                elif request.params["result"] == "failure":
                    cases.filter("success =", False)
            if request.params.has_key("open_only") and request.params["open_only"] == "1":
                cases.filter("closed =", False)
                c.open_only = True
            else:
                c.open_only = False
            if request.params.has_key("testsuite"):
                cases.filter("testsuite =", db.Key(request.params["testsuite"]))
            if request.params.has_key("platform"):
                cases.filter("platform =", request.params["platform"])
            
            c.testrun = testrun
            c.cases = []
            c.all_platforms = []
            c.all_testsuites = {}
            for case in cases:
                c.cases.append(case) 
                if case.platform not in c.all_platforms:
                    c.all_platforms.append(case.platform)
                if not c.all_testsuites.has_key(str(case.testsuite.key())):
                    c.all_testsuites[str(case.testsuite.key())] = case.testsuite.name
            c.all_platforms.sort()
            c.all_testsuites = c.all_testsuites.items()
            c.name = name
            
            return render("testrun/show.html")
        
    def batch(self):
        batch_set = {}
        for key, value in request.params.iteritems():
            if key.startswith("remarks-"):
                key = key[8:]
                if not batch_set.has_key(key):
                    batch_set[key] = {}
                batch_set[key]['remarks'] = value 
            elif key.startswith("success-"):
                key = key[8:]
                if not batch_set.has_key(key):
                    batch_set[key] = {}
                batch_set[key]['success'] = value
                
        c.batch = [] 
        for key, value in batch_set.iteritems():
            if value.has_key('success') and (value['success'] == 'True' or  value['success'] == 'False'):
                case = TestCaseResult.get(db.Key(key))
                case.closed = True
                case.success = False
                if value['success'] == 'True':
                    case.success = True
                if value.has_key('remarks'):
                    case.remarks = value['remarks']
                case.put()
                c.batch.append(case)
        
        return render("/testrun/batch.html") 